package cn.devcat.sso.util;

import cn.devcat.sso.entity.DevcatMenu;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class MenuTreeBuild {

    public List<DevcatMenu> nodeList;

    public MenuTreeBuild(List<DevcatMenu> nodeList){
        this.nodeList = nodeList;
    }

    public List<DevcatMenu> getRootNode(){
        return nodeList.stream().filter(item->"0".equals(item.getParentId())).collect(Collectors.toList());
    }

    public List<DevcatMenu> buildTree() {
        List<DevcatMenu> menuNode = new ArrayList<>();
        for(DevcatMenu rootMenu: getRootNode()){
            //构建子树
            rootMenu = buildChildMenu(rootMenu);
            menuNode.add(rootMenu);
        }
        menuNode.sort(Comparator.comparingInt(DevcatMenu::getMenuSort));
        return menuNode;
    }

    public DevcatMenu buildChildMenu(DevcatMenu menu){
        List<DevcatMenu> childMenu = new ArrayList<>();
        for(DevcatMenu m : nodeList){
            if(m.getParentId().equals(menu.getId())){
                childMenu.add(buildChildMenu(m));
            }
        }
        menu.setSubMenuList(childMenu);
        return menu;
    }
}
